/*
 * Copyright (C) 2008-2011 CBDP Consortium
 * 
 * All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.
 * 
 * This software consists of contributions made by many individuals, 
 * listed below:
 *
 * Author: 	Xabier Laiseca <xabier.laiseca@deusto.es>
 * 			David Ausín <david.ausin@deusto.es>
 */
package cbdp.server.contextreasoner.internal.containers;

import java.net.URL;

import cbdp.server.contextreasoner.impl.contextmanager.online.JenaContextManager;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.sdb.SDBFactory;
import com.hp.hpl.jena.sdb.Store;
import com.hp.hpl.jena.sdb.StoreDesc;

public class SDBOntologyContainer extends BaseOntologyContainer
{
	private final static String SDB_CONFIGURATION_FILE = "/resources/configuration/sdb.ttl";
	
	private Store store;
	
	@Override
	public void load()
	{
		setOntModel(createOntModelFromDB());
	}
	
	private OntModel createOntModelFromDB()
	{
		final String sdbConfigurationFile = (getConfiguration().getStorageConfigurationFileLocation() != null)?
				getConfiguration().getStorageConfigurationFileLocation():
				SDB_CONFIGURATION_FILE;
		
		final URL sdbConfigurationFileUrl = JenaContextManager.class.getResource(sdbConfigurationFile);
		final Model sdbConfigurationModel = ModelFactory.createDefaultModel();
		sdbConfigurationModel.read(sdbConfigurationFileUrl.toString(), "TTL" );
		final StoreDesc sdbStoreDesc = StoreDesc.read(sdbConfigurationModel); 
		
		store = SDBFactory.connectStore(sdbStoreDesc);
	    final Model model = SDBFactory.connectDefaultModel(store);
	    
	    return ModelFactory.createOntologyModel(getOntModelSpec(), model);
	}

	@Override
	public void close()
	{
		getOntModel().close();
		store.close();
	}
}
